<?php ob_start();?>
<?php
include("plus/theme_options.php");?>
<?php
//Avatar 默认头像
add_filter( 'avatar_defaults', 'newgravatar' );
function newgravatar ($avatar_defaults) {
$myavatar = get_bloginfo('template_directory') . '/images/avatar.png';
$avatar_defaults[$myavatar] = "来访者";
return $avatar_defaults;
}

function blog_substr($text, $length)  {
	$j = 0;
	for($i=0; $i<$length; $i++)
	{
		$chr = substr($text, $i, 1);
		if (ord($chr) > 127) { //SBC case
			$j++;
		}
	}
	while($j % 3 !== 0) { $j--;$length--;}
	$str = substr($text, 0, $length);
	return $str;
}

function blog_clear_content($text,   $length)  {
	$text = strip_tags($text);
	return ' - '.blog_substr($text, $length).'...';
}


// Produces threaded/nested comments structure, requires wordpress 2.7&higher
function blog_comment($comment, $args, $depth) {

   $GLOBALS['comment'] = $comment; ?>
  
<?php 	global $commentcount;
	$page = ( !empty($in_comment_loop) ) ? get_query_var('cpage') : get_page_of_comment( $comment->comment_ID, $args );
	$cpp=get_option('comments_per_page');//获取每页评论显示数量
	if(!$commentcount) { //初始化楼层计数器
		if ($page > 1) {
		$commentcount = $cpp * ($page - 1);
		} else {
		$commentcount = 0;//如果评论还没有分页，初始值为0
		}
	}
?>
   <li class="<?php
/* Only use the authcomment class from style.css if the user_id is 1 (admin) */
if (1 == $comment->user_id)
$oddcomment = "author-comment";
echo $oddcomment;
?>" id="comment-<?php comment_ID() ?>">
   
   <div class="comment_body">
      <?php $add_below = 'comment'; ?>
		<div class="comment_meta"><div>
		<?php echo get_avatar( $comment, 34 ); ?></div><span>
				<a rel="nofollow" target="_blank" href="/plus/go.php?url=<?php comment_author_url(); ?>"><?php comment_author(); ?></a>
				
	</span>
		</div>
 <div class="comment_content"> 
		<?php comment_text() ?>
		<div class="comm_meta_div">
		<span class="commentmetadata">
<?php comment_reply_link(array_merge( $args, array('add_below' => $add_below, 'reply_text' => __('回复他/她', 'blog'), 'depth' => $depth, 'max_depth' => $args['max_depth']))) ?>
		</span>			
		<?php if(!$parent_id = $comment->comment_parent) {printf('此古生物在第 %1$s 座岛屿顺利着落。', ++$commentcount);} ?> [<?php printf('%1$s %2$s', get_comment_date('Y-n-j'), get_comment_time('H:i') );?>]　
	</div> 		
  </div>
  </div>
  
<?php
}

function blog_end_comment() {
		echo '</li>';
}

//Determine if it is an original post
function blog_is_original() {
	$tags = get_the_tags();
	if($tags) {
		foreach($tags as $tag) {
			if(strpos( $tag->name, "Original") !== false ) return true;
		}
	}

	$cats = get_the_category();
	if($cats) {
		foreach($cats as $cat) {
			if(strpos($cat->name, "Original") !== false ) return true;
		}
	}
	return false;
}

// Make index of sticky posts
function blog_sticky_index() {
	global $sticky_index;

	$c = '';

	if (is_sticky()) {
		$c = $c . ++$sticky_index;
		return $c;
	}
	else
		return '-not';
}

function blog_title_margin($index)
{
	if(is_numeric($index))
	{
		$index = 43 * ($index - 1);
		$c = 'margin-top:'.$index.'px';
		return $c;
	}
}


// Produces an avatar image with the hCard-compliant photo class
function blog_commenter_link() {
	global $comment_ids;
	$commenter = get_comment_author_link();
	if ( ereg( '<a[^>]* class=[^>]+>', $commenter ) ) {
		$commenter = ereg_replace( '(<a[^>]* class=[\'"]?)', '\\1url ' , $commenter );
	} else {
		$commenter = ereg_replace( '(<a )/', '\\1class="url "' , $commenter );
	}
	$avatar_email = get_comment_author_email();
	$avatar_size = apply_filters( 'avatar_size', '34' ); // Available filter: avatar_size
	$avatar = str_replace( "class='avatar", "class='avatar avatar-34 photo", get_avatar( $avatar_email, $avatar_size ) );
	if ( $comment_floor = $comment_ids[get_comment_id()] )
		$comment_floor = '#'.$comment_floor;
	echo $avatar . '' .$comment_floor. '</div><span>' . $commenter . '</span>';
}
//版权时间设置
function comicpress_copyright() {
global $wpdb;
$copyright_dates = $wpdb->get_results("
SELECT
YEAR(min(post_date_gmt)) AS firstdate,
YEAR(max(post_date_gmt)) AS lastdate
FROM
$wpdb->posts
WHERE
post_status = 'publish'
");
$output = '';
if($copyright_dates) {
$copyright = "&copy; " . $copyright_dates[0]->firstdate;
if($copyright_dates[0]->firstdate != $copyright_dates[0]->lastdate) {
$copyright .= '-' . $copyright_dates[0]->lastdate;
}
$output = $copyright;
}
return $output;
}

//评论邮件回复
// 评论回应邮件通知
function comment_mail_notify($comment_id) {
  $admin_notify = '1'; // admin 要不要收回复通知 ( '1'=要 ; '0'=不要 )
  $admin_email = get_bloginfo ('admin_email'); // $admin_email 可改为你指定的 e-mail.
  $comment = get_comment($comment_id);
  $comment_author_email = trim($comment->comment_author_email);
  $parent_id = $comment->comment_parent ? $comment->comment_parent : '';
  global $wpdb;
  if ($wpdb->query("Describe {$wpdb->comments} comment_mail_notify") == '')
    $wpdb->query("ALTER TABLE {$wpdb->comments} ADD COLUMN comment_mail_notify TINYINT NOT NULL DEFAULT 0;");
  if (($comment_author_email != $admin_email && isset($_POST['comment_mail_notify'])) || ($comment_author_email == $admin_email && $admin_notify == '1'))
    $wpdb->query("UPDATE {$wpdb->comments} SET comment_mail_notify='1' WHERE comment_ID='$comment_id'");
  $notify = $parent_id ? get_comment($parent_id)->comment_mail_notify : '0';
  $spam_confirmed = $comment->comment_approved;
  if ($parent_id != '' && $spam_confirmed != 'spam' && $notify == '1') {
    $wp_email = 'no-reply@' . preg_replace('#^www\.#', '', strtolower($_SERVER['SERVER_NAME'])); // e-mail 发出点, no-reply 可改为可用的 e-mail.
    $to = trim(get_comment($parent_id)->comment_author_email);
    $subject = '您好！您在 [' . get_option("blogname") . '] 的留言有了新的回应!!';
    $message = '
    <div style="background-color:#eef2fa; border:1px solid #d8e3e8; font-size:10px;color:#111; padding:0 15px; -moz-border-radius:5px; -webkit-border-radius:5px; -khtml-border-radius:5px;">
      <p><span style="color: #025982">' . trim(get_comment($parent_id)->comment_author) . ' </span><span style="color: #717475">, 您好!</span></p>
      <p><span style="color: #717475">您曾在《' . get_the_title($comment->comment_post_ID) . '》的留言：</span><br /></p><p><span style="color: #54595a">'
       . trim(get_comment($parent_id)->comment_content) . '<//span></p>
      <p><span style="color: #717475">' . trim($comment->comment_author) . ' 给您的回应：</span><br /></p><p><span style="color: #54595a">'
       . trim($comment->comment_content) . '<br /></span></p>
      <p><span style="color: #717475">您可以点击 </span><span style="color: #025982;a:link{color:#025982}"><a href="' . htmlspecialchars(get_comment_link($parent_id)) . '">查看回应完整內容</a></span></p>
      <p><span style="color: #717475">欢迎您再次访问 </span><span style="color: #025982" a:link{color:#025982}><a href="' . get_option('home') . '">' . get_option('blogname') . '</a></span></p>
      <p><span style="color: #717475">（此邮件由 彼岸世界 邮件系统自动发出，请勿回复.）</span></p>
    </div>';
    $from = "From: \"" . get_option('blogname') . "\" <$wp_email>";
    $headers = "$from\nContent-Type: text/html; charset=" . get_option('blog_charset') . "\n";
    wp_mail( $to, $subject, $message, $headers );
    //echo 'mail to ', $to, '<br/> ' , $subject, $message; // for testing
  }
}
add_action('comment_post', 'comment_mail_notify');

// 自动勾选 
function add_checkbox() {
  echo '<div style="display:none"><input type="checkbox" name="comment_mail_notify" id="comment_mail_notify" value="comment_mail_notify" checked="checked" style="margin-left:0px;" /><label for="comment_mail_notify">有人回复时邮件通知我</label></div>';
}
add_action('comment_form', 'add_checkbox');




//single 上面翻页
function pagenavitop($before = '', $after = '', $prelabel = '', $nxtlabel = '', $pages_to_show = 9, $always_show = true) {

global $request, $posts_per_page, $wpdb, $paged;
if(empty($prelabel)) { $prelabel = '上页';
} if(empty($nxtlabel)) {
$nxtlabel = '下一页';
//} $half_pages_to_show = round($pages_to_show/2);
} $half_pages_to_show = round($pages_to_show);
if (!is_single()) {
if(!is_category()) { 
preg_match('#FROM\s(.*)\sORDER BY#siU', $request, $matches); 

} else {
preg_match('#FROM\s(.*)\sGROUP BY#siU', $request, $matches); }


$fromwhere = $matches[1];
$numposts = $wpdb->get_var("SELECT COUNT(DISTINCT ID) FROM $fromwhere");
$max_page = ceil($numposts /$posts_per_page);
if(empty($paged)) {
$paged = 1;
}
if($max_page > 1 || $always_show) {
 if ($paged >= ($pages_to_show-1)) {
echo '<a href="'.get_pagenum_link().'">页首</a>'; }
previous_posts_link($prelabel);
for($i = $paged - $half_pages_to_show; $i <= $paged + $half_pages_to_show; $i++) { if ($i >= 1 && $i <= $max_page) { if($i == $paged) {
echo "<span class=\"current\">$i</span>";
} else {
echo '<a href="'.get_pagenum_link($i).'">'.$i.'</a>'; }

}
}
next_posts_link($nxtlabel, $max_page);
if (($paged+$half_pages_to_show) < ($max_page)) {
echo '<a href="'.get_pagenum_link($max_page).'">末页</a>'; }
echo "$before <span style=\"color:#999999\"> (共 $max_page 页) </span>";
echo "$after";
}
}
}


//single 下面翻页
function pagenavidown($before = '', $after = '', $prelabel = '', $nxtlabel = '', $pages_to_show = 9, $always_show = true) {
global $request, $posts_per_page, $wpdb, $paged;
if(empty($prelabel)) { $prelabel = '上页';
} if(empty($nxtlabel)) {
$nxtlabel = '下一页';
//} $half_pages_to_show = round($pages_to_show/2);
} $half_pages_to_show = round($pages_to_show);
if (!is_single()) {
if(!is_category()) {
preg_match('#FROM\s(.*)\sORDER BY#siU', $request, $matches); } else {
preg_match('#FROM\s(.*)\sGROUP BY#siU', $request, $matches); }
$fromwhere = $matches[1];
$numposts = $wpdb->get_var("SELECT COUNT(DISTINCT ID) FROM $fromwhere");
$max_page = ceil($numposts /$posts_per_page);
if(empty($paged)) {
$paged = 1;
}
if($max_page > 1 || $always_show) {
 if ($paged >= ($pages_to_show-1)) {
echo '<a href="'.get_pagenum_link().'">页首</a>'; }
previous_posts_link($prelabel);
for($i = $paged - $half_pages_to_show; $i <= $paged + $half_pages_to_show; $i++) { if ($i >= 1 && $i <= $max_page) { if($i == $paged) {
echo "<span class=\"current_nav_under\">$i</span>";
} else {
echo '<a href="'.get_pagenum_link($i).'">'.$i.'</a>'; }

}
}
next_posts_link($nxtlabel, $max_page);
if (($paged+$half_pages_to_show) < ($max_page)) {
echo '<a href="'.get_pagenum_link($max_page).'">末页</a>'; 
}
echo "$before <span style=\"color:#999999\"> (共 $max_page 页) </span>";
echo "$after";
}
}
}


//相关文章
//Related Posts
function wp_get_related_posts() {
	global $wpdb, $post,$table_prefix;
	$limit = 7; //显示几条相关文章
	if(!$post->ID){return;}
	$now = current_time('mysql', 1);
	$tags = wp_get_post_categories($post->ID, array('all_with_object_id'));
	$taglist = "'" . $tags[0]. "'";
	$tagcount = count($tags);
	if ($tagcount > 1) {
		for ($i = 1; $i < $tagcount; $i++) {
			$taglist = $taglist . ", '" . $tags[$i]->term_id . "'";
		}
	}
    $limitclause = "LIMIT $limit";
	$q = "SELECT p.ID, p.post_title, p.post_content,p.post_excerpt, p.post_date,  p.comment_count FROM $wpdb->term_taxonomy t_t, $wpdb->term_relationships t_r, $wpdb->posts p WHERE t_t.taxonomy ='category' AND t_t.term_taxonomy_id = t_r.term_taxonomy_id AND t_r.object_id  = p.ID AND (t_t.term_id IN ($taglist)) AND p.ID != $post->ID AND p.post_status = 'publish' AND p.post_date_gmt < '$now' ORDER BY RAND() DESC, p.post_date_gmt DESC $limitclause;";
	$related_posts = $wpdb->get_results($q);
	$output = "";
	if (!$related_posts) {
		$output  .= '<li>没找到相关文章，有也不给你看。</li>';
	}
foreach ($related_posts as $related_post ) {
		$dateformat = get_option('date_format');
		$output .= '<li>';
		$output .= '<a href="'.get_permalink($related_post->ID).'">'.wptexturize($related_post->post_title).'</a>';
		$output .= '</li>';
	}
	$output = '<h3>还有这些可能你也想看看：</h3><ul class="same-cat-post">' . $output . '</ul>';
	return $output;
	}
	function wp_related_posts_attach($content) {
		  if (is_feed()) {
			  $output = wp_get_related_posts();
			  $content = $content . $output;
		   }
	return $content;
	}
	add_filter('the_content', 'wp_related_posts_attach',100);

//本月热门文章
function get_timespan_month($mode = '', $limit = 8, $days = 30, $display = true) {
global $wpdb, $post;
$limit_date = current_time('timestamp') - ($days*86400);
$limit_date = date("Y-m-d H:i:s",$limit_date);
$where = '';
$str = '';
if(!empty($mode) && $mode != 'both') {
$where = "post_type = '$mode'";
} else {
$where = '1=1';
}
$most_viewed = $wpdb->get_results("SELECT DISTINCT $wpdb->posts.*, (meta_value+0) AS views FROM $wpdb->posts LEFT JOIN $wpdb->postmeta ON $wpdb->postmeta.post_id = $wpdb->posts.ID WHERE post_date < '".current_time('mysql')."' AND post_date > '".$limit_date."' AND $where AND post_status = 'publish' AND meta_key = 'views' AND post_password = '' ORDER  BY views DESC LIMIT $limit");
$str='<ul>';
if($most_viewed) { 
$output = $pre_HTML;
$i=1;
foreach ($most_viewed as $post) {
$post_title = get_the_title();
$post_views = intval($post->views);
$post_views = number_format($post_views);
$str .= "<li><span class=\"tabNum\">$i</span><a href=\"".get_permalink()."\">$post_title</a> ".__('', 'wp-postviews')."</li>";
$i++;
}

} 

else {
$str = '<ul><li>'.__('N/A', 'wp-postviews').'</li></ul>'."\n";

}$str.='</ul>';

if($display) {
echo $str;
} else {
return $str;
}
}
//本月热门文章结束



//本年热门文章
function get_timespan_year($mode = '', $limit = 8, $days = 365, $display = true) {
global $wpdb, $post;
$limit_date = current_time('timestamp') - ($days*86400);
$limit_date = date("Y-m-d H:i:s",$limit_date);
$where = '';
$str = '';
if(!empty($mode) && $mode != 'both') {
$where = "post_type = '$mode'";
} else {
$where = '1=1';
}
$most_viewed = $wpdb->get_results("SELECT DISTINCT $wpdb->posts.*, (meta_value+0) AS views FROM $wpdb->posts LEFT JOIN $wpdb->postmeta ON $wpdb->postmeta.post_id = $wpdb->posts.ID WHERE post_date < '".current_time('mysql')."' AND post_date > '".$limit_date."' AND $where AND post_status = 'publish' AND meta_key = 'views' AND post_password = '' ORDER  BY views DESC LIMIT $limit");
$str='<ul>';
if($most_viewed) { 
$output = $pre_HTML;
$i=1;
foreach ($most_viewed as $post) {
$post_title = get_the_title();
$post_views = intval($post->views);
$post_views = number_format($post_views);
$str .= "<li><span class=\"tabNum\">$i</span><a href=\"".get_permalink()."\">$post_title</a> ".__('', 'wp-postviews')."</li>";
$i++;
}

} 

else {
$str = '<ul><li>'.__('N/A', 'wp-postviews').'</li></ul>'."\n";

}$str.='</ul>';

if($display) {
echo $str;
} else {
return $str;
}
}
//本年热门文章结束




// 获取月度热评  
function get_most_viewed_month($posts_num=8, $days=30){   
    global $wpdb;   
 
    $sql = "SELECT `ID` , `post_title` , `comment_count` FROM $wpdb->posts  
            WHERE `post_type` = 'post' AND TO_DAYS( now( ) ) - TO_DAYS( `post_date` ) < $days  
            ORDER BY `comment_count` DESC LIMIT 0 , $posts_num ";   
 
    $posts = $wpdb->get_results($sql);   
	
	$output = $pre_HTML;
$i=1;
	
    foreach ($posts as $post){   
        $output .= "\n<ul><li><span class=\"tabNum\">$i</span>
		
		<a href= \"".get_permalink($post->ID)."\" rel=\"bookmark\" title=\"\" >".$post->post_title."</a></li></ul>";   
    $i++;}   
	
    echo $output;   
}   

// 获取年度热评  
function get_most_viewed_year($posts_num=8, $days=365){   
    global $wpdb;   
 
    $sql = "SELECT `ID` , `post_title` , `comment_count` FROM $wpdb->posts  
            WHERE `post_type` = 'post' AND TO_DAYS( now( ) ) - TO_DAYS( `post_date` ) < $days  
            ORDER BY `comment_count` DESC LIMIT 0 , $posts_num ";   
 
    $posts = $wpdb->get_results($sql);   
	
	$output = $pre_HTML;
$i=1;
	
    foreach ($posts as $post){   
        $output .= "\n<ul><li><span class=\"tabNum\">$i</span>
		
		<a href= \"".get_permalink($post->ID)."\" rel=\"bookmark\" title=\"\" >".$post->post_title."</a></li></ul>";   
    $i++;}   
	
    echo $output;   
}   


//手动随机文章
function matt_random_redirect() {
	global $wpdb;
	
	$query = "SELECT ID FROM $wpdb->posts WHERE post_type = 'post' AND post_password = '' AND 	post_status = 'publish' ORDER BY RAND() LIMIT 1";

	if ( isset( $_GET['random_cat_id'] ) ) {
		$random_cat_id = (int) $_GET['random_cat_id'];
		$query = "SELECT DISTINCT ID FROM $wpdb->posts AS p INNER JOIN $wpdb->term_relationships AS tr ON (p.ID = tr.object_id AND tr.term_taxonomy_id = $random_cat_id) INNER JOIN  $wpdb->term_taxonomy AS tt ON(tr.term_taxonomy_id = tt.term_taxonomy_id AND taxonomy = 'category') WHERE post_type = 'post' AND post_password = '' AND 	post_status = 'publish' ORDER BY RAND() LIMIT 1";
	}

	if ( isset( $_GET['random_post_type'] ) ) {
		$post_type = preg_replace( '|[^a-z]|i', '', $_GET['random_post_type'] );
		$query = "SELECT ID FROM $wpdb->posts WHERE post_type = '$post_type' AND post_password = '' AND 	post_status = 'publish' ORDER BY RAND() LIMIT 1";
	}

	$random_id = $wpdb->get_var( $query );

	wp_redirect( get_permalink( $random_id ) );
	exit;
}

if ( isset( $_GET['random'] ) )
	add_action( 'template_redirect', 'matt_random_redirect' ); 
	?>